<template>
	<view class="container">
		<view class="search cu-bar" ref="search">
			<u-search
				@click="show = true"
				:show-action="false"
				placeholder="搜索"
				:disabled="true"
			></u-search>
		</view>
		<view>
				<u-popup v-model="show" mode="top" length="45%">
					<view
					class="text-blue padding-left-sm padding-top-sm"
					style="font-size: 18px"
					>
					<u-icon name="/static/common/img/find.png" size="64"></u-icon>
					<text class="padding-left-sm text-blue">查询条件</text>
					</view>
					<u-form class="form" :model="query" ref="uForm" label-position="left">
					<!-- <u-form-item class="text-bold" label="是否完成:" prop="cinvcode" label-width="200">
									<js-select v-model="query.cinvcode" dict-type="sys_yes_no" placeholder="请选择是否完成"></js-select>
								</u-form-item> -->
					<u-form-item
						class="text-bold"
						label="存货编码:"
						prop="basInv.cinvcode"
						label-width="200"
					>
						<u-input
						placeholder="请输入"
						v-model="query['basInv.cinvcode']"
						type="text"
						maxlength="200"
						></u-input>
					</u-form-item>
					<u-form-item
						class="text-bold"
						label="存货名称:"
						prop="basInv.cinvname"
						label-width="200"
					>
						<u-input
						placeholder="请输入"
						v-model="query['basInv.cinvname']"
						type="text"
						maxlength="200"
						></u-input>
					</u-form-item>
					</u-form>
					<view class="footer">
					<u-button class="btn" type="primary" @click="submit">查询</u-button>
					<u-button class="btn margin-top-lg" @click="reset">重置</u-button>
					</view>
				</u-popup>
			</view>
		<view class="wrap">
			<scroll-view
			scroll-y="true"
			@scrolltolower="loadMore"
			:refresher-enabled="true"
			:scrolltolower-enabled="true"
			:refresher-triggered="triggered"
			@refresherrefresh="refresherrefresh"
			@scrolltoupper="refresherrefresh"
			class="scroll-view-class"
			:style="{ height: computedScrollViewHeight }"
			>
			
				<view class="cu-item shadow margin raduis" style="position: relative;" v-for="(item,index) in list" @click="selectRw(index)">
					<view class="cu-form-group text-xl text-bold">
					<view class="title flex">
						<view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px	;">
							{{ index + 1 }}
						</view>
						<view>订单行号</view>
					</view>
					<!-- {{ item.scOrder.sortNum ? '#' + item.scOrder.sortNum : ''}}  -->
					<view class="flex-sub"> {{ item.scOrder ? item.scOrder.code : '' }} {{ item.scOrder ? item.scOrder.sortNum ? '#' + item.scOrder.sortNum : '' : '' }} </view>
					</view>
					<!-- <view class="cu-form-group">
						<view class="title">工序：</view>
						<view class="flex-sub">{{ item.basOper.name }} {{  item.basOper.code ? '(' + item.basOper.code + ')' : ''  }}</view>
					</view> -->
					<view class="cu-form-group">
						<view class="title">存货编码：</view>
						<view class="flex-sub">{{ item.basInv.cinvcode }}</view>
					</view>
					<view class="cu-form-group">
						<view class="title">存货名称：</view>
						<view class="flex-sub">{{ item.basInv.cinvname }}</view>
					</view>
					<view class="cu-form-group">
						<view class="title">规格型号：</view>
						<view class="flex-sub">{{ item.basInv.cinvstd }}</view>
					</view>
					<view class="cu-form-group">
						<view class="title">计划数：</view>
						<view class="flex-sub">{{ item.scOrder ? item.scOrder.iqty : '' }}</view>
					</view>
					<view style="position: absolute;right: 20rpx;z-index:9999;top: 14%; transform: translateY(-50%);"  >
						<image src="/static/image/select.png" style="width: 30px; height: 30px" v-if="checkedIndex === index"></image>
						<image src="/static/image/unSelect.png" style="width: 30px; height: 30px" v-else></image>
						<!--  -->
					</view>
					
				</view>
				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
				<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 100%;"></u-empty>
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group">
				<!-- round -->
				<button class="cu-btn  bg-confirm lg margin-left " @click="confirm">确定</button>
			
			</view>
			<custom-modal
			ref="customModal"
			v-if="showModal"
			:initial-message="modalMessage"
			@update:close="onModalClose"
			></custom-modal>
			
		</view>
	</view>

</template>

<script>
import CustomModal from "@/pages/mes/components/CustomModal.vue";
export default {
	components: {
		CustomModal,
	},
	data() {
		return {
			loadStatus: "loadmore",
			triggered: false,
			query: {
			  pageNo: 1,
			  pageSize: 20,
			  // orderBy: "a.create_date desc",
			},
			list : [],
			checkedIndexes: [],
			checkedIndex: null,
			scrollViewHeight: 0,
			showModal: false,
			modalMessage: "",
			show: false,
			modid:''
		}
	},
	onLoad(e){
		console.log(e,e.modid === 'undefined')
		// this.modid = e.modid === 'undefined' ? '' :  e.modid
		// if(e.modid === 'undefined'){
		// 	this.query.modid = ''
		// }else{
		// 	this.query.modid = e.modid
		// }
		this.query.pageNo = 1;
		this.query.lineCode = e.lineCode
		setTimeout(()=>{
			this.loadData();	
		},500)
		console.log('onLoad',this.list)
		
	},
	async  mounted() {
		this.calculateScrollViewHeight()		
	},
	computed: {
	  computedScrollViewHeight() {
		return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
	  },
	},
	methods:{	
		async refresherrefresh() {
		  this.triggered = true;
		  this.query.pageNo = 1;
		  await this.loadData();
		  setTimeout(() => {
			this.triggered = false;
		  }, 500);
		},
		loadMore() {
		  this.loadStatus = "loading";
		  setTimeout(() => {
			this.query.pageNo += 1;
			this.loadData("add");
		  }, 100);
		},
		loadData(type) {
		  
		  this.$u.api.kst.getTlTaskByLineCode(this.query).then((res) => {
			if (res.data.length < 20 || res.data.length == 0) {
			  this.loadStatus = "nomore";
			}
			var data = res.data;
			if (type == "add") {
			  for (var i = 0; i < data.length; i++) {
				this.list.push(data[i]);
				this.$nextTick(() => {
					console.log('DOM 更新完成');
				});
			  }
			} else {
			  this.list = data;
			  this.$nextTick(() => {
				console.log('DOM 更新完成');
			});
			}
			
			console.log('loadData',this.list )
		  });
		},
		selectRw(index){
			// 如果当前index已经在数组中，移除它；否则添加它
			// const currentIndexExists = this.checkedIndexes.includes(index);
			// // 使用Set来避免在大数组中频繁的includes检查，提高效率
			// const updatedIndexes = new Set(this.checkedIndexes);
			
			// if (currentIndexExists) {
			// 	updatedIndexes.delete(index);
			// 	console.log('取消选中', index);
			// } else {
			// 	updatedIndexes.add(index);
			// 	console.log('选中', index);
			// }
			// // 将Set转换回Array并赋值给checkedIndexes
			// this.checkedIndexes = Array.from(updatedIndexes);
			if (this.checkedIndex === index) {
				this.checkedIndex = null; // Deselect if already selected
			} else {
				this.checkedIndex = index; // Select the new index
			}

		},
		async calculateScrollViewHeight() {
		  try {
		// 等待头部高度计算完成
			  
			  // 计算btn-group 高度
			  // 获取屏幕高度
			  const systemInfo = uni.getSystemInfoSync();
			  const screenHeight = systemInfo.windowHeight;
			  const searchHeight =  this.$refs['search'] ?  this.$refs['search'].$el ? this.$refs['search'].$el.offsetHeight : 0 : 0
			  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 109 : 0
			  // 计算scroll-view高度
			  this.scrollViewHeight = screenHeight - ( btnOffsetHeight + searchHeight );
		  } catch (error) {
			console.error('Error while calculating ScrollView height:', error);
		  }
		},
		confirm(){
			if(this.checkedIndex === null){
				this.showCustomModal("请选择报工任务").then((res) => {
					
				})
			}else{
				this.showCustomModal("确认当前任务报工").then((res) => {
					if(res){
						// 返回上一页
						// const selectedItems = this.checkedIndexes.map((index) => {
						// 	const item = this.list[index];
						// 	item.isDelFlag = true; // 添加isDelFlag属性并设置为true
						// 	return item;
						// });
						this.list[this.checkedIndex].isDelFlag = true; // 添加isDelFlag属性并设置为true
						const selectedItemsItem = this.list[this.checkedIndex];
						const selectedItems = [selectedItemsItem];
						
						
						// 使用navigateBack返回上一页，并传递参数
						uni.navigateBack({
							delta: 1, // 返回上一页
							success: () => {
								uni.$emit('selectedItems', selectedItems);
							},
							fail: (err) => {
								console.error('返回上一页失败', err);
							}
						});
					}
					
				})					
			}

		},
		async showCustomModal(message) {
		  this.modalMessage = message;
		  this.showModal = true;
		  // 模拟同步等待用户操作
		  return new Promise((resolve) => {
			this.onModalClose = (result) => {
			  this.modalResult = result;
			  this.showModal = false;
			  resolve(this.modalResult);
			};
		  });
		},
		onModalClose(result) {
		  this.$emit("update:close", result);
		},
		submit() {
			setTimeout(() => {
				this.query.pageNo = 1;
				this.loadData();
			}, 100);
			this.show = false
		},
		reset() {
			this.query = {
					pageNo: 1,
					pageSize: 20,
					modid : this.modid == undefined ? '' :this.modid
			};
			this.loadData();
		},
	}
}	
</script>

<style scoped>
.title{
	width: 240rpx;
}
.bg-confirm {
  background: #3e97b0;
  color: #ffffff;
}
</style>